package com.sayice.coursetable.logic.network;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.Objects;

import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 课程相关服务
 */
public abstract class CourseService {
    private static final String PERSONAL_COURSE_URL = "http://jwgl.csuft.edu.cn/jsxsd/xskb/xskb_list.do";
    private static final String CLASS_COURSE_URL = "http://jwgl.csuft.edu.cn/jsxsd/kbcx/kbxx_xzb_ifr";
    private static final String TEACHER_COURSE_URL = "http://jwgl.csuft.edu.cn/jsxsd/kbcx/kbxx_teacher_ifr";

    /**
     * 获取个人课程页面（Jsoup Document）
     *
     * @param username 用户名
     * @param password 密码
     * @return 返回 Jsoup 解析页面后得到的 Document对象，若获取失败则返回 null
     */
    public static Document getPersonalCoursePage(String username, String password) {
        String courseHtml = LoginService.loginAndRequestHtml(username, password, httpClient -> {
            String html = null;
            Request courseRequest = new Request.Builder().url(PERSONAL_COURSE_URL).get().build();
            try (Response courseResponse = httpClient.newCall(courseRequest).execute()){
                html = Objects.requireNonNull(courseResponse.body()).string();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return html;
        });
        return courseHtml == null ? null : Jsoup.parse(courseHtml);
    }

    /**
     * 获取班级课程页面（Jsoup Document）
     *
     * @param username  用户名
     * @param password  密码
     * @param grade     年级（入学年份）
     * @param majorCode 专业代号
     * @param classNum  班级号
     * @return 返回 Jsoup 解析页面后得到的 Document对象，若获取失败则返回 null
     */
    public static Document getClassCoursePage(String username, String password, int grade, String majorCode, int classNum) {
        String courseHtml = LoginService.loginAndRequestHtml(username, password, httpClient -> {
            String html = null;
            FormBody requestBody = new FormBody.Builder()
                    .add("sknj", String.valueOf(grade))
                    .add("skzy", majorCode)
                    .build();
            Request courseRequest = new Request.Builder()
                    .url(CLASS_COURSE_URL)
                    .post(requestBody)
                    .build();
            try(Response courseResponse = httpClient.newCall(courseRequest).execute()) {
                String body = Objects.requireNonNull(courseResponse.body()).string();
                Elements courseElements = Jsoup.parse(body).select(
                        "table[id=kbtable]>tbody>tr:eq(" + (classNum + 1) + ")");
                if (courseElements.size() != 0) {
                    html = courseElements.get(0).outerHtml();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return html;
        });
        return courseHtml == null ? null : Jsoup.parseBodyFragment(courseHtml);
    }

    /**
     * 获取教师课程页面（Jsoup Document）
     *
     * @param username    用户名
     * @param password    密码
     * @param teacherName 教师名
     * @return 返回 Jsoup 解析页面后得到的 Document对象，若获取失败则返回 null
     */
    public static Document getTeacherCoursePage(String username, String password, String teacherName) {
        String courseHtml = LoginService.loginAndRequestHtml(username, password, httpClient -> {
            String html = null;
            Request courseRequest = new Request.Builder().url(TEACHER_COURSE_URL).get().build();
            try (Response courseResponse = httpClient.newCall(courseRequest).execute()) {
                String body = Objects.requireNonNull(courseResponse.body()).string();
                Elements courseElements = Jsoup.parse(body).select(
                        "table[id=kbtable]>tbody>tr:contains(" + teacherName + ")");
                if (courseElements.size() != 0) {
                    html = courseElements.get(0).outerHtml();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return html;
        });
        return courseHtml == null ? null : Jsoup.parseBodyFragment(courseHtml);
    }
}
